from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os

# 根据运行环境动态设置数据库路径
# 优先使用环境变量，否则使用绝对路径
if os.getenv("DATABASE_URL"):
    SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL")
else:
    # 使用绝对路径确保数据库文件位置正确
    project_root = "/root/devworks/torrentfileschecker"
    db_path = os.path.join(project_root, "data", "torrent_checker.db")
    SQLALCHEMY_DATABASE_URL = f"sqlite:///{db_path}"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    db.database_path = SQLALCHEMY_DATABASE_URL
    try:
        yield db
    finally:
        db.close()
